<?php
class cours extends Controller{

	var $models = array('Cour');

	function index(){
		$d = array();
		$d['cours'] = $this->Cour->find();

		$this->loadModel('Categorie');
		$d['categories'] = $this->Categorie->find(array(
			'order' => 'libelle'
		));

		$this->loadModel('Classe');
		$d['classes'] = $this->Classe->find(array(
			'order' => 'libelle'
		));

		if ($this->Session->isLogged()){
			$this->layout = 'user';
		}
		$this->set($d);
		$this->render('index');
	}

	function categorie($id){
		$d = array();
		$d['cours'] = $this->Cour->find(array(
			'conditions' => "categorie LIKE '$id'"
		));

		$this->loadModel('Categorie');
		$d['cat'] = $this->Categorie->findFirst(array(
			'conditions' => "codeCat LIKE '$id'",
			'order' => 'libelle'
		));

		if ($this->Session->isLogged()){
			$this->layout = 'user';
		}
		$this->set($d);
		$this->render('categorie');
	}

	function view($id){
		$d = array();
		$d['cour'] = $this->Cour->findFirst(array(
			'conditions' => 'id='.$id
		));

		$codeCateg = $d['cour']->categorie;
		$user = $d['cour']->user;

		$this->loadModel('Categorie');
		$d['cat'] = $this->Categorie->findFirst(array(
			'conditions' => "codeCat LIKE '$codeCateg'",
			'order' => 'libelle'
		));

		$this->loadModel('User');
		$d['user'] = $this->User->findFirst(array(
			'conditions' => 'id='.$user
		));

		if ($this->Session->isLogged()){
			$this->layout = 'user';
		}
		$this->set($d);
		$this->render('view');
	}

	function user_edit($id=null){
		$d = array();
		if ($id){
			$d['cour'] = $this->Cour->findFirst(array(
				'fields' => 'id, titre, contenu, classe, categorie, fichier',
				'conditions' => 'id='.$id
			));
		}
		if (isset($_POST) && !empty($_POST)){
			$this->Cour->save($_POST);
			if (isset($_FILES) && !empty($_FILES['fichier']['name'])){
				$file = $_FILES['fichier'];
				$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
				if ($extension == "jpg" || $extension == "jpeg" || $extension == "pdf"){
					move_uploaded_file($file['tmp_name'], ROOT.'files/cours/'.$file['name']);
				}
				$id = isset($id) ? $id : $this->Cour->db->lastInsertId();
				$fichier = array(
					'id' => $id,
					'fichier' => $file['name']
				);
				$this->Cour->save($fichier);
			}
			$this->Session->setFlash('Votre cour à bien été enregistré');
			$this->redirect('users/index');
		}
		$this->loadModel('Categorie');
		$d['categories'] = $this->Categorie->find(array(
			'order' => 'libelle'
		));
		$this->loadModel('Classe');
		$d['classes'] = $this->Classe->find(array(
			'order' => 'libelle'
		));
		$this->layout = 'user';
		$this->set($d);
		$this->render('user_edit');
	}

	function user_delete($id){
		$this->Cour->delete($id);
		$this->Session->setFlash('Cour supprimé', 'alert');
		$this->redirect('users/index');
	}
}